/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mlbs.session.generated;

import com.mlbs.entity.Device;
import com.mlbs.entity.Preferences;
import com.mlbs.entity.Usertable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

/**
 *
 * @author mckd87
 */
@PersistenceContext(name="mlbs-ejbPU", unitName="mlbs-ejbPU", type=PersistenceContextType.EXTENDED)
@Stateless
public class PreferencesFacade implements PreferencesFacadeRemote{
    @EJB
    private DeviceFacadeRemote deviceFacade;
    @PersistenceContext(unitName="mlbs-ejbPU")
    private EntityManager em;

    public void create(Preferences preferences) {
        em.persist(preferences);
    }

    public void edit(Preferences preferences) {
        em.merge(preferences);
    }

    public void remove(Preferences preferences) {
        em.remove(em.merge(preferences));
    }

    public Preferences find(Object id) {
        return em.find(com.mlbs.entity.Preferences.class, id);
    }

    public List<Preferences> findAll() {
        return em.createQuery("select object(o) from Preferences as o").getResultList();
    }

    public void updateCacheSettings(String imei, String cache) {
        updatePreferences(imei, "cache", cache);
        
    }

    public void updatePreferences(String imei, String key, String value) {
        Device device = deviceFacade.find(imei);
        Usertable user = device.getUserid();
        Collection s = findAll();
        Iterator prefItr = s.iterator();
        int j = s.size();
        while(prefItr.hasNext()){
            Preferences p = (Preferences)prefItr.next();
            System.out.println(p.getUserId().getDisplayName());
            if(p.getDeviceid().getDeviceid().equals(device.getDeviceid())){
                if(p.getKeyName().equalsIgnoreCase(key)){
                    p.setValue(value);
                    edit(p);
                    return;
                }
            }
        }
   
        Preferences preferences = new Preferences(new Integer(j+1));
        preferences.setCacheFlag(true);
        preferences.setDeviceid(device);
        preferences.setUserId(user);
        preferences.setKeyName(key);
        preferences.setValue(value);
        create(preferences);
    }
}
